<template>
  <a-modal :title="formTile + '工艺库'" :visible="true" width="60%" :footer="null" @cancel="reset">
    <div class="main">
      <a-card>
        <a-row type="flex" justify="start" align="top">
          <a-col :span="24">
            <a-form :form="form" @submit="handleSubmit" :labelCol="formItemLayout.labelCol"
              :wrapperCol="formItemLayout.wrapperCol">
              <a-form-item label="部位">
                <a-select allow-clear :required="true" show-search placeholder="请选择部位" @change="changePart"
                  :filterOption="filterOption" v-decorator="[
                    'partId',
                    {
                      rules: [{ required: true, message: '请选择部位!' }]
                    }
                  ]">
                  <a-select-option :value="item.code" v-for="(item, index) in partList" :key="index">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="做法">
                <a-select allow-clear :required="true" show-search :filterOption="filterOption" @change="changeOper"
                  placeholder="请选择做法" v-decorator="[
                    'operId',
                    {
                      rules: [{ required: true, message: '请选择做法!' }]
                    }
                  ]">
                  <a-select-option :value="item.code" v-for="(item, index) in operList" :key="index">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="图片" help="只支持图片格式" style="text-align:left" :required="true">
                <a-upload name="file" list-type="picture-card" :multiple="true" class="avatar-uploader"
                  :data="{ type: 1 }" :fileList="fileList" @change="handleChange" :action="uploadUrl">
                  <div>
                    <a-icon type="plus" />
                    <div class="ant-upload-text">
                      上传图片
                    </div>
                  </div>
                </a-upload>
                <!-- <JImageUpload style="display:flex;flex-wrap: wrap;width:100%" :fileSize="5" :uploadParams="getUploadParams()" :accept="'image/*'" @fileChange="fileXcxImageChange" v-model="fileList"></JImageUpload> -->
              </a-form-item>
              <a-form-item label="描述" :required="true">
                <a-textarea allow-clear placeholder="请输入描述" :rows="4" :maxLength="500" v-decorator="[
                  'description',
                  {
                    rules: [{ required: true, message: '请输入描述!' }]
                  }
                ]"></a-textarea>

              </a-form-item>
            </a-form>
            <a-table :columns="columns" :data-source="brands">
              <template slot="brand" slot-scope="txt, record">
                <span v-for="item, index in record.brand" :key="index">
                  <span v-for="subitem, index in brandList" :key="index">
                    <a-tag color="blue" v-if="item == subitem.code">{{ subitem.name }}</a-tag>
                  </span>
                </span>
              </template>
              <template slot="xl" slot-scope="txt, record">
                <span v-for="item, index in record.xl" :key="index">
                  <span v-for="subitem, index in xlList" :key="index">
                    <a-tag color="cyan" v-if="item == subitem.code">{{ subitem.name }}</a-tag>
                  </span>
                </span>
              </template>
              <template slot="material" slot-scope="txt, record">
                <span v-for="item, index in record.material" :key="index">
                  <span v-for="subitem, index in materialList" :key="index">
                    <a-tag color="purple" v-if="item == subitem.code">{{ subitem.name }}</a-tag>
                  </span>
                </span>
              </template>
              <template slot="thick" slot-scope="txt, record">
                <span v-for="item, index in record.thick" :key="index">
                  <span v-for="subitem, index in thickList" :key="index">
                    <a-tag color="orange" v-if="item == subitem.code">{{ subitem.name }}</a-tag>
                  </span>
                </span>
              </template>
              <template slot="action" slot-scope="txt, record,i">
                <a class="mr-10" @click="edit(record, i)">
                  <a-icon type="edit" />编辑
                </a>
                <a-popconfirm :title="`确定要删除该项吗?`" @confirm="deleteRecord(i)">
                  <a class="mr-10">
                    <a-icon type="delete" />删除
                  </a>
                </a-popconfirm>
              </template>

            </a-table>

          </a-col>
        </a-row>
        <div class="steps-action">
          <a-button type="primary" @click="reset">返回</a-button>
          <div>
            <a-button type="link" @click="showMore">
              <a-icon type="plus" /> 批量添加
            </a-button>
            <a-button :loading="loading" type="primary" style="margin-left: 8px" @click="handleSubmit">
              提交
            </a-button>
          </div>
        </div>
      </a-card>
    </div>
    <a-modal v-model="visible" title="批量添加" width="70%" @ok="handleOk">
      <a-form :form="form3" @submit="handleOk" :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol">
        <a-form-item label="品牌" :required="true">
          <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">
            全选
          </a-checkbox>
          <a-checkbox-group style="width: 100%;" @change="onChange" v-model="brand">
            <a-row>
              <a-col :span="6" v-for="item, index in brandList" :key="index">
                <a-checkbox :value="item.code">
                  {{ item.name }}
                </a-checkbox>
              </a-col>

            </a-row>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="小类" :required="true">
          <a-checkbox :indeterminate="indeterminate1" :checked="checkAll1" @change="onCheckAllChange1">
            全选
          </a-checkbox>
          <a-checkbox-group style="width: 100%;" v-model="xl" @change="onChange1">
            <a-row>
              <a-col :span="6" v-for="item, index in xlList" :key="index">
                <a-checkbox :value="item.code">
                  {{ item.name }}
                </a-checkbox>
              </a-col>

            </a-row>
          </a-checkbox-group>

        </a-form-item>
        <a-form-item label="材质" :required="true">
          <a-checkbox :indeterminate="indeterminate2" :checked="checkAll2" @change="onCheckAllChange2">
            全选
          </a-checkbox>
          <a-checkbox-group style="width: 100%;" v-model="material" @change="onChange2">
            <a-row>
              <a-col :span="6" v-for="item, index in materialList" :key="index">
                <a-checkbox :value="item.code">
                  {{ item.name }}
                </a-checkbox>
              </a-col>

            </a-row>
          </a-checkbox-group>

        </a-form-item>
        <a-form-item label="厚薄" :required="true">
          <a-checkbox :indeterminate="indeterminate3" :checked="checkAll3" @change="onCheckAllChange3">
            全选
          </a-checkbox>
          <a-checkbox-group style="width: 100%;" v-model="thick" @change="onChange3">
            <a-row>
              <a-col :span="6" v-for="item, index in thickList" :key="index">
                <a-checkbox :value="item.code">
                  {{ item.name }}
                </a-checkbox>
              </a-col>

            </a-row>
          </a-checkbox-group>

        </a-form-item>
      </a-form>
    </a-modal>
  </a-modal>
</template>

<script>
import { createList, updatelist, getDictChildList, getDetail } from '@api/rd/index'
import { uploadUrl } from '@api/rd/index.js'
import globalData from '@/assets/js/common'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import { brandList } from '../../marketingCenter/components/brandList'
const columns = [
  {
    title: '品牌',
    scopedSlots: { customRender: 'brand' }
  },
  {
    title: '小类',
    scopedSlots: { customRender: 'xl' }
  },
  {
    title: '材质',
    width: 80,
    scopedSlots: { customRender: 'material' }
  },
  {
    title: '厚薄',
    width: 80,
    scopedSlots: { customRender: 'thick' }
  },
  {
    title: '操作',
    width: 160,
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: { JImageUpload },

  props: {
    content: {
      type: Object,
      default: null
    }
  },

  data() {
    return {
      id: '',
      index: '',
      columns,
      uploadUrl,
      visible: false,
      loading: false,
      idEdit: false,
      partList: [],
      operList: [],
      fileList: [],
      imgurl: '',
      brandList: [],
      firstForm: {},
      selectBrand: [],
      nextForm: {},
      finalForm: {},
      partId: '',
      operId: '',
      imageUrl: '',
      indeterminate: true,
      checkAll: false,
      indeterminate1: true,
      indeterminate2: true,
      indeterminate3: true,
      checkAll1: false,
      checkAll2: false,
      checkAll3: false,
      form: this.$form.createForm(this),
      form1: this.$form.createForm(this),
      form2: this.$form.createForm(this),
      form3: this.$form.createForm(this),
      current: 0,
      brand: [],
      steps: ['选择部位做法', '设置步骤', '设置关联属性'],
      fileds: [],
      brands: [],
      xl: [],
      xlList: [],
      material: [],
      materialList: [],
      thick: [],
      thickList: [],
      formItemLayout: {
        labelCol: {
          xl: { span: 5 }
        },
        wrapperCol: {
          xl: { span: 15 }
        }
      }
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo || null
    }
  },
  created() {
    const { content } = this.$props
    console.log(content)
    if (content) {
      this.formTile = '编辑'
      this.id = content.id
      this.idEdit = true
      this.getDetail()
    } else {
      this.formTile = '新增'
      // this.addBrand()
    }
    this.getPartList()
    this.getOperList()
    this.getBrandList()
    this.getXlList()
    this.getMList()
    this.getTList()
  },
  methods: {
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    fileXcxImageChange(list) {
      console.log('list', list)
      this.imgurl = list[0].url
    },
    reset() {
      this.form.resetFields()
      this.$emit('close')
    },
    closeBrand() {
      this.selectBrand = []
      this.visible = false
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    handleChange(info, item, index) {
      let fileList = [...info.fileList]
      this.fileList = [...fileList]
      if (info.file.status === 'uploading') {
        return
      }
      if (info.file.status === 'done') {
        let list = fileList.map(file => {
          if (file.response) {
            file.url = file.response.data.url
          }
          return file
        })
        this.fileList = list.slice(-1)
      }
      if (info.file.response.code != '200') {
        this.$message.error(info.file.response.msg)
        info.file.status = 'error'
        this.fileList.map((item) => {
          if (item.thumbUrl == info.file.thumbUrl) {
            item.status = 'error'
          }
        })
      }
    },
    changePart(value) {
      this.partId = value
      // this.partList.map(item => {
      //   if (item.name == value) {
      //     this.partId = item.code
      //   }
      // })
    },
    changeOper(value) {
      this.operId = value
      // this.operList.map(item => {
      //   if (item.name == value) {
      //     this.operId = item.code
      //   }
      // })
    },
    handleOk(e) {
      e.preventDefault()
      if (!this.xl.length) {
        this.$message.error('请选择小类！')
      } else if (!this.brand.length) {
        this.$message.error('请选择品牌！')
      } else {
        this.submit3()
      }
    },
    deleteRecord(i) {
      this.brands = this.brands.filter((item, index) => index != i)
    },
    submit3() {
      if (this.index || this.index === 0) {
        const obj = {
          groupId: null,
          brand: this.brand,
          xl: this.xl,
          material: this.material,
          thick: this.thick
        }
        this.$set(this.brands, this.index, obj)
        this.visible = false
      } else {
        const obj = {
          groupId: null,
          brand: this.brand,
          xl: this.xl,
          material: this.material,
          thick: this.thick
        }
        this.brands.push(obj)
        this.visible = false
      }
      // if (!this.brands[0].brand) {
      //   this.brands = arr
      // } else {
      //   this.brands = this.brands.concat(arr)
      // }
      // this.visible = false
    },
    showMore() {
      this.visible = true
      this.brand = []
      this.xl = []
      this.material = []
      this.thick = []
      this.index = ''
    },
    edit(record, i) {
      this.visible = true
      this.brand = record.brand
      this.xl = record.xl
      this.material = record.material
      this.thick = record.thick
      this.index = i
    },
    remove(index) {
      let { fileds } = this
      fileds.splice(index, 1)
      this.fileds = fileds
    },
    removeBrand(index) {
      let { brands } = this
      brands.splice(index, 1)
      this.brands = brands
    },
    addBrand() {
      const obj = { brand: undefined, xl: undefined }
      let { brands } = this
      brands.push(obj)
      this.brands = brands
    },
    onChange(checkedList) {
      this.indeterminate = !!checkedList.length && checkedList.length < this.brandList.length
      this.checkAll = checkedList.length === this.brandList.length
    },
    onCheckAllChange(e) {
      const arr = []
      this.brandList.map(item => {
        arr.push(item.id)
      })
      this.brand = e.target.checked ? arr : []
      this.indeterminate = false
      this.checkAll = e.target.checked
    },
    onChange1(checkedList) {
      this.indeterminate1 = !!checkedList.length && checkedList.length < this.xlList.length
      this.checkAll1 = checkedList.length === this.xlList.length
    },
    onCheckAllChange1(e) {
      const arr = []
      this.xlList.map(item => {
        arr.push(item.id)
      })
      this.xl = e.target.checked ? arr : []
      this.indeterminate1 = false
      this.checkAll1 = e.target.checked
    },
    onChange2(checkedList) {
      this.indeterminate2 = !!checkedList.length && checkedList.length < this.materialList.length
      this.checkAll2 = checkedList.length === this.materialList.length
    },
    onCheckAllChange2(e) {
      const arr = []
      this.materialList.map(item => {
        arr.push(item.id)
      })
      this.material = e.target.checked ? arr : []
      this.indeterminate2 = false
      this.checkAll2 = e.target.checked
    },
    onChange3(checkedList) {
      this.indeterminate3 = !!checkedList.length && checkedList.length < this.thickList.length
      this.checkAll3 = checkedList.length === this.thickList.length
    },
    onCheckAllChange3(e) {
      const arr = []
      this.thickList.map(item => {
        arr.push(item.id)
      })
      this.thick = e.target.checked ? arr : []
      this.indeterminate3 = false
      this.checkAll3 = e.target.checked
    },

    async getDetail() {
      const params = {
        id: this.id
      }
      try {
        const res = await getDetail('lib', params)
        if (res.code == 200) {
          const content = res.data
          this.$nextTick(() => {
            console.log(content);
            this.brands = content.craftRelation
            this.partId = content.partId
            this.operId = content.operId
            this.imgurl = content.imgurl
            // this.fileList.push(content.imgurl)
            if (content.imgurl) {
              const obj = {
                name: 'pic.png',
                uid: content.imgurl,
                status: 'done',
                url: content.imgurl
              }
              this.fileList.push(obj)
            }
            this.form.setFieldsValue({ partId: content.partId, operId: content.operId, description: content.description })
          })
        } else {
          if (res.msg) {
            this.$message.error(res.msg)
          } else {
            this.$message.error('获取详情失败！')
          }
        }
      } catch (error) {
        this.$message.error('获取部位列表失败！')
      }
    },
    async getPartList() {
      const params = {
        name: 'GY_PART'
      }
      try {
        const res = await getDictChildList('dict', params)
        if (res.code == 200) {
          this.partList = res.data
        } else {
          if (res.msg) {
            this.$message.error(res.msg)
          } else {
            this.$message.error('获取部位列表失败！')
          }
        }
      } catch (error) {
        this.$message.error('获取部位列表失败！')
      }
    },
    async getOperList() {
      const params = {
        name: 'GY_OPER'
      }
      try {
        const res = await getDictChildList('dict', params)
        if (res.code == 200) {
          this.operList = res.data
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error('获取做法列表失败！')
      }
    },
    async getBrandList() {
      const params = {
        name: 'BRAND'
      }
      try {
        const res = await getDictChildList('dict', params)
        if (res.code == 200) {
          this.brandList = res.data
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error('获取品牌列表失败！')
      }
    },

    async getXlList() {
      const params = {
        name: 'XL'
      }
      try {
        const res = await getDictChildList('dict', params)
        if (res.code == 200) {
          this.xlList = res.data
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error('获取小类列表失败！')
      }
    },
    async getMList() {
      const params = {
        name: 'GY_MATERIAL'
      }
      try {
        const res = await getDictChildList('dict', params)
        if (res.code == 200) {
          this.materialList = res.data
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error('获取小类列表失败！')
      }
    },
    async getTList() {
      const params = {
        name: 'GY_THICK'
      }
      try {
        const res = await getDictChildList('dict', params)
        if (res.code == 200) {
          this.thickList = res.data
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error('获取小类列表失败！')
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.submit(values)
        }
      })
      // this.current += 1
    },
    async submit(values) {
      console.log(values)
      this.loading = true
      const params = {
        imgurl: this.fileList[0].url,
        partId: this.partId,
        operId: this.operId,
        description: values.description
      }
      params.craftRelationGroup = this.brands
      const { realname } = this.userInfo
      params.operator = realname
      if (this.id) {
        params.id = this.id
      }
      try {
        const res = this.idEdit ? await updatelist('lib', params) : await createList('lib', params)
        if (res.code == 200) {
          this.$message.success(this.idEdit ? '修改工艺库成功！' : '新建工艺库成功！')
          this.reset()
        } else {
          this.$message.warning(res.msg)
        }
      } catch (error) {
        this.$message.warning('操作失败！')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
  // margin-bottom: 20px;
}

.ml-20 {
  margin-left: 20px;
}

.steps-content {
  margin-top: 16px;
  min-height: 200px;
  text-align: center;
  padding-top: 50px;
}

.steps-action {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
}

.ant-upload-picture-card-wrapper {
  width: 20%;
}

.ant-upload-picture-card-wrapper[data-v-7206a2ce] {
  width: 100%;
}

.dynamic-delete-button {
  cursor: pointer;
  font-size: 24px;
  color: #999;
  margin: 50px 5px;
  transition: all 0.3s;
}

.dynamic-delete-button:hover {
  color: #777;
}

.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
